package benny_driving_ser.util;

import java.lang.reflect.Field;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import benny_driving_ser.dao.SessionAttributeParamsDao;
import benny_driving_ser.dao.impl.CheckPWDVersionImpl;
import benny_driving_ser.entity.SessionAttributeDriId;
import benny_driving_ser.entity.SessionAttributeUserId;
import benny_driving_ser.servlet.listener.SessionListener;

public class SessionUtil {
	private SessionUtil() {

	}

	private static class SessionUtilHolder {
		private static SessionUtil instance = new SessionUtil();
	}

	public static SessionUtil getInstance() {
		return SessionUtilHolder.instance;
	}

	public HttpServletResponse getSessionId(HttpServletRequest request,
			HttpServletResponse response, SessionAttributeParamsDao id) {
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(3600 * 24 * 3);
		String[] paramNames = ReflectUtil.getAttribute(id);
		// String paramName = "";
		// for (int i = 0; i < paramNames.length; i++) {
		// paramName = paramNames[i];
		// }
		session.setAttribute(paramNames[0], id.getValue());
		session.setAttribute(paramNames[1], id.getPWDVersion());
		Cookie cookie = new Cookie("JSESSIONID", session.getId());
		cookie.setMaxAge(3600);
		response.addCookie(cookie);
		return response;
	}

	public SessionAttributeDriId verifySessionIdForDri(
			HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(3600 * 24 * 3);
		String id = (String) session.getAttribute("driId");
		String pwdVersion = (String) session.getAttribute("pwdVersion");

		if (null == id
				|| null == pwdVersion
				|| !CheckPWDVersionImpl.getInstance().verifyPWDVersion(id,
						pwdVersion))
			return null;
		return new SessionAttributeDriId(id, pwdVersion);
	}

	public SessionAttributeUserId verifySessionIdForUser(
			HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(3600 * 24 * 7);
		String id = (String) session.getAttribute("userId");
		String pwdVersion = (String) session.getAttribute("pwdVersion");
		if (null == id || null == pwdVersion)
			return null;
		return new SessionAttributeUserId(id, pwdVersion);
	}
}
